package com.coszero.utils.base

import android.content.Context
import android.view.LayoutInflater
import androidx.recyclerview.widget.RecyclerView

/**
 * @author xmqian
 * ListView或GrideView的Adapter父类
 * @version 1
 */
abstract class BaseRecyclerAdapter<VH : RecyclerView.ViewHolder?>(
    protected var context: Context,
    @JvmField protected var list: MutableList<*>?
) :
    RecyclerView.Adapter<VH>() {
    protected var inflater: LayoutInflater = LayoutInflater.from(context)
    @JvmField
    protected var mContext: Context = context

    override fun getItemId(i: Int): Long {
        return i.toLong()
    }

    //替换数据源
    fun setData(data: MutableList<*>?) {
        this.list = data
        notifyDataSetChanged()
    }

    fun refresh(data: List<*>?) {
        if (data != null) {
            if (data.size > 0) {
                if (list === data) { // 两个list 是同一个
                    notifyDataSetChanged()
                    return
                } else {
                    list!!.clear()
                    list!!.addAll(data)
                }
            } else {
                list!!.clear()
            }
        } else {
            list!!.clear()
        }
        notifyDataSetChanged()
    }


    /**
     * 清理List集合
     */
    fun clean() {
        list!!.clear()
        notifyDataSetChanged()
    }

    /**
     * 添加集合
     *
     * @param list
     */
    fun addAll(list: List<*>?) {
        if (list != null) {
            if (list.size > 0) {
                if (this.list == list) { // 两个list 是同一个
                    notifyDataSetChanged()
                    return
                } else {
                    this.list!!.addAll(list)
                }
            }
            notifyDataSetChanged()
        }
    }

    /**
     * 添加集合到指定位置
     *
     * @param list
     * @param position
     */
    fun addAll(list: List<*>, position: Int) {
        this.list!!.addAll(position, list)
        notifyDataSetChanged()
    }

    /**
     * 返回List集合
     *
     * @return
     */
    fun getList(): List<*>? {
        return list
    }

    companion object {
        protected fun <V> isEmptyLs(list: List<V>?): Boolean {
            return null == list || list.size <= 0
        }
    }
}
